package com.mind.ridge.service.front.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mind.ridge.mapper.front.AddressBookMapper;
import com.mind.ridge.service.front.AddressBookService;
import com.mind.ridge.utils.R;
import org.springframework.stereotype.Service;
import com.mind.ridge.pojo.front.AddressBook;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Mind
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    @Override
    public R<AddressBook> setDefaultAddress(AddressBook addressBook, HttpSession session) {
        //获取当前用户的id
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, session.getAttribute("userId"));
        //将该用户所有其他的地址默认设置为0
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        this.update(wrapper);

        //再将该地址设置为默认地址
        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        this.updateById(addressBook);
        return R.success(addressBook);
    }

    @Override
    public R<AddressBook> getDefaultAddress(HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = this.getOne(lqw);
        return R.success(addressBook);
    }

    @Override
    public R<List<AddressBook>> addressList(HttpSession session) {
        long userId = (long) session.getAttribute("userId");

        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, userId);
        List<AddressBook> list = this.list(lqw);
        return R.success(list);
    }

    @Override
    public R<String> addAddress(AddressBook addressBook, HttpSession session) {
        if (addressBook == null) {
            return R.error("ERROR");
        }
        long userId = (long) session.getAttribute("userId");
        addressBook.setUserId(userId);
        boolean success = this.save(addressBook);
        return success ? R.success("添加成功") : R.error("添加失败");
    }
}
